﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.DAL.DTOs;
using Microsoft.SharePoint;
using office = Microsoft.Office.DocumentManagement.DocumentSets;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Support.Enums;

namespace MS.InformationManagement.BLL.ShippingControlTemplates
{
    public class MarkCopiaAsDeliveredCommand : IBaseCommand
    {
        #region Fields

        IEnumerable<PlanillasDTO> _foundItems;
        List<SPListItem> _itemsBackup = new List<SPListItem>();
        string _currentUser;

        #endregion

        #region Constructors

        public MarkCopiaAsDeliveredCommand(IEnumerable<PlanillasDTO> foundItems)
        {
            _foundItems = foundItems;
        }

        #endregion

        #region Implemented Methods

        public void Execute()
        {
            _currentUser = SPContext.Current.Web.CurrentUser.LoginName;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb currentWeb = currentSite.OpenWeb())
                    {
                        currentWeb.AllowUnsafeUpdates = true;
                        currentSite.AllowUnsafeUpdates = true;

                        foreach (var entity in _foundItems)
                        {
                            SPList documentsList = currentWeb.Lists[entity.IdList];
                            SPListItem documentCopiaListItem = documentsList.GetItemById(entity.IdItem);
                            _itemsBackup.Add(documentCopiaListItem);

                            //Update fields
                            documentCopiaListItem[CustomSiteColumns.FLD_COPY_DELIVERED] = true;
                            documentCopiaListItem[CustomSiteColumns.FLD_COPY_DEVUELTO] = false;

                            //Update Logs
                            DeliveryTraceabilityEntry deliveryLogEntry = this.getDeliverEntity(entity, "");
                            documentCopiaListItem.UpdateDeliveryLog(deliveryLogEntry);
                            documentCopiaListItem.Log(string.Empty, DateTime.Now, TraceableOperation.Recibido, _currentUser, string.Empty);


                            documentCopiaListItem.Update();

                            SendEmail(entity.UsuarioAsignado ,entity.NoRadicado, entity.Destinatario);
                        }

                        currentSite.AllowUnsafeUpdates = false;
                        currentWeb.AllowUnsafeUpdates = false;
                    }
                }
            }); 
        }

        public void Undo()
        {
            _currentUser = SPContext.Current.Web.CurrentUser.LoginName;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb currentWeb = currentSite.OpenWeb())
                    {
               

                        for (int i = 0; i < _itemsBackup.Count; i++)
                        {
                            SPList documentsList = _itemsBackup[i].ParentList;

                            documentsList.ParentWeb.AllowUnsafeUpdates = true;
                            documentsList.ParentWeb.Site.AllowUnsafeUpdates = true;


                            SPListItem documentCopiaListItem = documentsList.GetItemById(_itemsBackup[i].ID);
                            documentCopiaListItem[CustomSiteColumns.FLD_COPY_DELIVERED] = _itemsBackup[i][CustomSiteColumns.FLD_COPY_DELIVERED];
                            documentCopiaListItem[CustomSiteColumns.FLD_COPY_DEVUELTO] = _itemsBackup[i][CustomSiteColumns.FLD_COPY_DEVUELTO];
                            documentCopiaListItem.Update();

                            documentsList.ParentWeb.AllowUnsafeUpdates = false;
                            documentsList.ParentWeb.Site.AllowUnsafeUpdates = false;
                        }
                    }
                }
            }); 
        }

        #endregion

        #region Private Methods

        private DeliveryTraceabilityEntry getDeliverEntity(PlanillasDTO currentEntity,  string department)
        {
            DeliveryTraceabilityEntry logEntry = new DeliveryTraceabilityEntry();
            logEntry.Address = currentEntity.Direccion;
            logEntry.Area = department;
            logEntry.City = currentEntity.Ciudad;
            logEntry.DateTime = DateTime.Now;
            logEntry.To = currentEntity.Destinatario;
            logEntry.Operation = DeliveryOperations.Recibido.ToString();
            logEntry.User = _currentUser;
            return logEntry;
        }

        private static void SendEmail(string UserLogin, string NumeroRadicado, string Destinatario)
        {
            string toField = new MS.InformationManagement.BLL.GestionDeUsuarios.GestionDeUsuariosBLL().getProperty(GlobalConstants.UP_EMAIL, UserLogin);
            string subject = "Correspondencia";
            string body = string.Format("La copia del radicado de salida {0} dirigido a {1} fue entregado exitosamente.", NumeroRadicado, Destinatario);
            EmailHelper.SendEmail(toField, subject, body);
        }

        #endregion
    }
}
